package com.Web.guardians;

import com.DAO.Impl.ClassDAOImpl;
import com.DAO.Impl.ClassTypeImpl;
import com.DAO.Impl.StudentDAOImpl;
import com.DAO.Impl.guardiansDAOImpl;
import com.entity.Class;
import com.entity.guardians;
import com.entity.stuAndMenu;
import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 20x
 * @date 2024 - 12 -10
 **/
@WebServlet("/ListGuardians")
public class ListGuardiansServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        int sizePage = 5;
        String where = (req.getParameter("where") == null)? "" : req.getParameter("where");
        String page = (req.getParameter("page") == null)? "1" : req.getParameter("page");
        String sortColumn = (req.getParameter("sortColumn") == null)? "" : req.getParameter("sortColumn");
        String sortOrder = (req.getParameter("sortOrder") == null)? "" : req.getParameter("sortOrder");
        int pageInt = Integer.parseInt(page);
        int currentPage = new guardiansDAOImpl().count(where);
        int totalPage = (int) Math.ceil((double) currentPage / sizePage);
        System.out.println(totalPage);
        List<guardians> guardiansList = new guardiansDAOImpl().getAll(where,pageInt,sizePage,sortColumn,sortOrder);
        String message = "获取数据失败";
        if(guardiansList.size() > 0){
            message = "获取数据成功";
        }
        // 创建一个包含所有需要发送的数据的对象
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("guardiansList", guardiansList);
        responseData.put("totalPage", totalPage);
        responseData.put("message", message);
        responseData.put("pageInt", pageInt);

        // 将对象转换为JSON字符串
        String jsonResponse = gson.toJson(responseData);
        out.write(jsonResponse);
        out.close();
    }
}
